package com.example.origin.finance.trade.dto.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.example.origin.finance.dto.XueqiuKline;
import com.example.origin.finance.trade.dto.Analyst;
import com.example.origin.finance.trade.dto.Conclusion;
import com.example.origin.finance.trade.dto.InfoResource;
import com.example.origin.finance.trade.dto.TradeRecord;
import com.example.origin.finance.trade.enums.Action;

import java.util.List;
import java.util.stream.Collectors;

public class RedUsJiJinAnalyst extends Analyst {
    @Override
    protected Conclusion conclusion() {
        InfoResource infoResource = getInfoResource();
        String code = infoResource.getCode();
        if (!getTradeRecordMap().containsKey(code)
                || getTradeRecordMap().get(code).stream().allMatch(TradeRecord::isSold)) {
            return new Conclusion(infoResource, buyFlag() ? Action.BUY : Action.NONE);
        }

        List<TradeRecord> tradeRecords = getTradeRecordMap().get(code);
        for (int i = tradeRecords.size() - 1; i >= 0; i--) {
            TradeRecord tradeRecord = tradeRecords.get(i);
            if (tradeRecord.isBought()) {
                if (sellFlag()) {
                    return new Conclusion(infoResource, Action.SELL);
                }
            }
        }
        return new Conclusion(infoResource, Action.NONE);
    }

    public boolean buyFlag() {
        if (getMoreKlines().size() < 9) {
            return false;
        }
        DateTime preMonth = DateUtil.offsetMonth(getKline().getTimestamp(), -1);
        if (DateUtil.compare(getMoreKlines().get(2).getTimestamp(), preMonth) <= 0) {
            return false;
        }
        Double avgClose = getMoreKlines().stream().limit(8).collect(Collectors.averagingDouble(XueqiuKline::getClose));

        if (getMoreKlines().get(0).getClose() > avgClose && getMoreKlines().get(0).getPercent()>0&& getMoreKlines().get(1).getPercent()>0) {
            return true;
        }
        return false;
    }


    public boolean sellFlag() {
        if (getMoreKlines().size() < 2) {
            return false;
        }
        Double avgClose = getMoreKlines().stream().limit(8).collect(Collectors.averagingDouble(XueqiuKline::getClose));
        if (getMoreKlines().get(0).getClose() < avgClose && getMoreKlines().get(0).getPercent()<0) {
            return true;
        }

        return false;
    }


}
